<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="MySQL,python,PyMySQL,">










<meta name="description" content="MySQLMySQL 是最流行的关系型数据库管理系统，在 WEB 应用方面 MySQL 是最好的 RDBMS(Relational Database Management System：关系数据库管理系统)应用软件之一。">
<meta name="keywords" content="MySQL,python,PyMySQL">
<meta property="og:type" content="article">
<meta property="og:title" content="Python_MySQL数据库">
<meta property="og:url" content="http://Anzusen.com/2019/04/17/Python-MySQL数据库/index.html">
<meta property="og:site_name" content="Anzhusen">
<meta property="og:description" content="MySQLMySQL 是最流行的关系型数据库管理系统，在 WEB 应用方面 MySQL 是最好的 RDBMS(Relational Database Management System：关系数据库管理系统)应用软件之一。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://anzusen.com/images/goin_mysql.png">
<meta property="og:image" content="http://anzusen.com/images/create_mysql.png">
<meta property="og:updated_time" content="2020-04-06T13:29:39.694Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python_MySQL数据库">
<meta name="twitter:description" content="MySQLMySQL 是最流行的关系型数据库管理系统，在 WEB 应用方面 MySQL 是最好的 RDBMS(Relational Database Management System：关系数据库管理系统)应用软件之一。">
<meta name="twitter:image" content="http://anzusen.com/images/goin_mysql.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://Anzusen.com/2019/04/17/Python-MySQL数据库/">





  <title>Python_MySQL数据库 | Anzhusen</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/ananzhusen/ananzhusen.github.io" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Anzhusen</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://Anzusen.com/2019/04/17/Python-MySQL数据库/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ananzhusen">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/touxiang.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Anzhusen">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python_MySQL数据库</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-17T20:48:13+08:00">
                2019-04-17
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/MYSQL数据库/" itemprop="url" rel="index">
                    <span itemprop="name">MYSQL数据库</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/04/17/Python-MySQL数据库/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/04/17/Python-MySQL数据库/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量 <i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.8k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  12
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="MySQL"><a href="#MySQL" class="headerlink" title="MySQL"></a>MySQL</h3><p>MySQL 是最流行的关系型数据库管理系统，在 WEB 应用方面 MySQL 是最好的 RDBMS(Relational Database Management System：关系数据库管理系统)应用软件之一。<br><a id="more"></a></p>
<h4 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h4><ul>
<li>安装教程查看链接<a href="http://www.runoob.com/mysql/mysql-install.html" target="_blank" rel="noopener">Windows 上安装 MySQL</a></li>
</ul>
<h4 id="MySQL常用命令"><a href="#MySQL常用命令" class="headerlink" title="MySQL常用命令"></a>MySQL常用命令</h4><p>以管理员身份打开cmd命令行工具，切换到你安装的mysql目录，这里是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">D:\Mysql\mysql-8.0.15-winx64\bin</span><br></pre></td></tr></table></figure>
<ol>
<li><p>启动：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">net start mysql</span><br></pre></td></tr></table></figure>
</li>
<li><p>登录</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mysql -h 主机名 -u 用户名 -p</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>如果是登录本机MySQL数据库，只需要输入以下命令：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mysql -u root -p</span><br></pre></td></tr></table></figure></p>
<p>接下来会让你输入登录密码：输入即可，如图所示：</p>
<p><img src="/images/goin_mysql.png" alt="启动并登录mysql数据库"></p>
<p>参数说明·：</p>
<ul>
<li>-h : 指定客户端所要登录的 MySQL 主机名(IP), 登录本机(localhost 或 127.0.0.1)该参数可以省略;</li>
<li>-u : 登录的用户名;</li>
<li>-p : 告诉服务器将会使用一个密码来登录, 如果所要登录的用户名密码为空, 可以忽略此选项。</li>
</ul>
<ol start="3">
<li>退出和停止</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">quit;//或者 exit</span><br><span class="line">...</span><br><span class="line">net stop mysql</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>修改密码</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mysqladmin -u用户名 -p旧密码 password 新密码</span><br></pre></td></tr></table></figure>
<ol start="5">
<li>创建数据库</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">create database &lt;数据库名&gt;;</span><br></pre></td></tr></table></figure>
<ol start="6">
<li>显示数据库</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">show databases;</span><br></pre></td></tr></table></figure>
<p><strong>注意</strong>：最后有个s</p>
<ol start="7">
<li>删除数据库</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">drop database &lt;数据库名&gt;</span><br></pre></td></tr></table></figure>
<p>如图所示：</p>
<p><img src="/images/create_mysql.png" alt="操作数据库"></p>
<ol start="8">
<li>更多常用命令访问：MySQL常用命令大全<a href="https://www.cnblogs.com/bluealine/p/7832219.html" target="_blank" rel="noopener">MySQL常用命令大全</a></li>
</ol>
<h4 id="mysql-connector"><a href="#mysql-connector" class="headerlink" title="mysql-connector"></a>mysql-connector</h4><p>使用 mysql-connector 来连接使用 MySQL， mysql-connector 是 MySQL 官方提供的驱动器。</p>
<h5 id="安装-1"><a href="#安装-1" class="headerlink" title="安装"></a>安装</h5><p>我们可以使用 pip 命令来安装 mysql-connector：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python -m pip install mysql-connector</span><br></pre></td></tr></table></figure></p>
<p>或者直接在pycharm的setting里面安装mysql-connect包</p>
<h5 id="操作"><a href="#操作" class="headerlink" title="操作"></a>操作</h5><h6 id="创建数据库连接"><a href="#创建数据库连接" class="headerlink" title="创建数据库连接"></a>创建数据库连接</h6><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> mysql.connector</span><br><span class="line"> </span><br><span class="line">mydb = mysql.connector.connect(</span><br><span class="line">  host=<span class="string">"localhost"</span>,       <span class="comment"># 数据库主机地址</span></span><br><span class="line">  user=<span class="string">"username"</span>,    <span class="comment"># 数据库用户名</span></span><br><span class="line">  passwd=<span class="string">"password"</span>   <span class="comment"># 数据库密码</span></span><br><span class="line">)</span><br><span class="line"> </span><br><span class="line">print(mydb)</span><br></pre></td></tr></table></figure>
<h6 id="创建数据库"><a href="#创建数据库" class="headerlink" title="创建数据库"></a>创建数据库</h6><p>创建数据库使用 “CREATE DATABASE” 语句，我们创建一个名为 first_db 的数据库：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> mysql.connector</span><br><span class="line"> </span><br><span class="line">mydb = mysql.connector.connect(</span><br><span class="line">  host=<span class="string">"localhost"</span>,</span><br><span class="line">  user=<span class="string">"root"</span>,</span><br><span class="line">  passwd=<span class="string">"123456"</span></span><br><span class="line">)</span><br><span class="line"> </span><br><span class="line">mycursor = mydb.cursor()</span><br><span class="line"> </span><br><span class="line">mycursor.execute(<span class="string">"CREATE DATABASE first_db"</span>)</span><br></pre></td></tr></table></figure>
<h6 id="查看数据库"><a href="#查看数据库" class="headerlink" title="查看数据库"></a>查看数据库</h6><p>输出所有数据库列表：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> mysql.connector</span><br><span class="line"> </span><br><span class="line">mydb = mysql.connector.connect(</span><br><span class="line">  host=<span class="string">"localhost"</span>,</span><br><span class="line">  user=<span class="string">"root"</span>,</span><br><span class="line">  passwd=<span class="string">"123456"</span></span><br><span class="line">)</span><br><span class="line"> </span><br><span class="line">mycursor = mydb.cursor()</span><br><span class="line"> </span><br><span class="line">mycursor.execute(<span class="string">"SHOW DATABASES"</span>)</span><br><span class="line"> </span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> mycursor:</span><br><span class="line">  print(x)</span><br></pre></td></tr></table></figure></p>
<p>我们可以直接连接数据库，如果数据库不存在，会输出错误信息：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> mysql.connector</span><br><span class="line"> </span><br><span class="line">mydb = mysql.connector.connect(</span><br><span class="line">  host=<span class="string">"localhost"</span>,</span><br><span class="line">  user=<span class="string">"root"</span>,</span><br><span class="line">  passwd=<span class="string">"123456"</span>,</span><br><span class="line">  database=<span class="string">"runoob_db"</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<h6 id="创建数据表"><a href="#创建数据表" class="headerlink" title="创建数据表"></a>创建数据表</h6><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> mysql.connector</span><br><span class="line"> </span><br><span class="line">mydb = mysql.connector.connect(</span><br><span class="line">  host=<span class="string">"localhost"</span>,</span><br><span class="line">  user=<span class="string">"root"</span>,</span><br><span class="line">  passwd=<span class="string">"123456"</span>,</span><br><span class="line">  database=<span class="string">"first_db"</span> <span class="comment"># 确保数据库first_db已存在</span></span><br><span class="line">)</span><br><span class="line">mycursor = mydb.cursor()</span><br><span class="line"> </span><br><span class="line">mycursor.execute(<span class="string">"CREATE TABLE sites (name VARCHAR(255), url VARCHAR(255))"</span>)</span><br></pre></td></tr></table></figure>
<h6 id="查看数据表是否已存在："><a href="#查看数据表是否已存在：" class="headerlink" title="查看数据表是否已存在："></a>查看数据表是否已存在：</h6><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> mysql.connector</span><br><span class="line"> </span><br><span class="line">mydb = mysql.connector.connect(</span><br><span class="line">  host=<span class="string">"localhost"</span>,</span><br><span class="line">  user=<span class="string">"root"</span>,</span><br><span class="line">  passwd=<span class="string">"123456"</span>,</span><br><span class="line">  database=<span class="string">"first_db"</span></span><br><span class="line">)</span><br><span class="line">mycursor = mydb.cursor()</span><br><span class="line"> </span><br><span class="line">mycursor.execute(<span class="string">"SHOW TABLES"</span>)</span><br><span class="line"> </span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> mycursor:</span><br><span class="line">  print(x)</span><br></pre></td></tr></table></figure>
<h6 id="主键设置"><a href="#主键设置" class="headerlink" title="主键设置"></a>主键设置</h6><p>创建表的时候我们一般都会设置一个主键（PRIMARY KEY）,<strong>主键起始值为 1，逐步递增。</strong></p>
<ol>
<li>如果我们的表已经创建，我们需要使用 ALTER TABLE 来给表添加主键：</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">给 sites 表添加主键。</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> mysql.connector</span><br><span class="line"> </span><br><span class="line">mydb = mysql.connector.connect(</span><br><span class="line">  host=<span class="string">"localhost"</span>,</span><br><span class="line">  user=<span class="string">"root"</span>,</span><br><span class="line">  passwd=<span class="string">"123456"</span>,</span><br><span class="line">  database=<span class="string">"first_db"</span></span><br><span class="line">)</span><br><span class="line">mycursor = mydb.cursor()</span><br><span class="line"> </span><br><span class="line">mycursor.execute(<span class="string">"ALTER TABLE sites ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY"</span>)</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>如果你还未创建 sites 表，可以直接使用以下代码创建。</li>
</ol>
<p>给表创建主键。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">import</span> mysql.connector</span><br><span class="line"> </span><br><span class="line">mydb = mysql.connector.connect(</span><br><span class="line">  host=<span class="string">"localhost"</span>,</span><br><span class="line">  user=<span class="string">"root"</span>,</span><br><span class="line">  passwd=<span class="string">"123456"</span>,</span><br><span class="line">  database=<span class="string">"first_db"</span></span><br><span class="line">)</span><br><span class="line">mycursor = mydb.cursor()</span><br><span class="line"> </span><br><span class="line">mycursor.execute(<span class="string">"CREATE TABLE sites (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), url VARCHAR(255))"</span>)</span><br></pre></td></tr></table></figure></p>
<h6 id="插入数据"><a href="#插入数据" class="headerlink" title="插入数据"></a>插入数据</h6><ol>
<li>向 sites 表插入一条记录。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> mysql.connector</span><br><span class="line"> </span><br><span class="line">mydb = mysql.connector.connect(</span><br><span class="line">  host=<span class="string">"localhost"</span>,</span><br><span class="line">  user=<span class="string">"root"</span>,</span><br><span class="line">  passwd=<span class="string">"123456"</span>,</span><br><span class="line">  database=<span class="string">"first_db"</span></span><br><span class="line">)</span><br><span class="line">mycursor = mydb.cursor()</span><br><span class="line"> </span><br><span class="line">sql = <span class="string">"INSERT INTO sites (name, url) VALUES (%s, %s)"</span></span><br><span class="line">val = (<span class="string">"RUNOOB"</span>, <span class="string">"https://www.runoob.com"</span>)</span><br><span class="line">mycursor.execute(sql, val)</span><br><span class="line"> </span><br><span class="line">mydb.commit()    <span class="comment"># 数据表内容有更新，必须使用到该语句</span></span><br><span class="line"> </span><br><span class="line">print(mycursor.rowcount, <span class="string">"记录插入成功。"</span>)</span><br></pre></td></tr></table></figure>
<p>执行代码，输出结果为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">1 记录插入成功</span><br></pre></td></tr></table></figure></p>
<ol start="2">
<li>批量插入<br>批量插入使用 executemany() 方法，该方法的第二个参数是一个元组列表，包含了我们要插入的数据：</li>
</ol>
<p>向 sites 表插入多条记录。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> mysql.connector</span><br><span class="line"> </span><br><span class="line">mydb = mysql.connector.connect(</span><br><span class="line">  host=<span class="string">"localhost"</span>,</span><br><span class="line">  user=<span class="string">"root"</span>,</span><br><span class="line">  passwd=<span class="string">"123456"</span>,</span><br><span class="line">  database=<span class="string">"first_db"</span></span><br><span class="line">)</span><br><span class="line">mycursor = mydb.cursor()</span><br><span class="line"> </span><br><span class="line">sql = <span class="string">"INSERT INTO sites (name, url) VALUES (%s, %s)"</span></span><br><span class="line">val = [</span><br><span class="line">  (<span class="string">'Google'</span>, <span class="string">'https://www.google.com'</span>),</span><br><span class="line">  (<span class="string">'Github'</span>, <span class="string">'https://www.github.com'</span>),</span><br><span class="line">  (<span class="string">'Taobao'</span>, <span class="string">'https://www.taobao.com'</span>),</span><br><span class="line">  (<span class="string">'stackoverflow'</span>, <span class="string">'https://www.stackoverflow.com/'</span>)</span><br><span class="line">]</span><br><span class="line"> </span><br><span class="line">mycursor.executemany(sql, val)</span><br><span class="line"> </span><br><span class="line">mydb.commit()    <span class="comment"># 数据表内容有更新，必须使用到该语句</span></span><br><span class="line"> </span><br><span class="line">print(mycursor.rowcount, <span class="string">"记录插入成功。"</span>)</span><br></pre></td></tr></table></figure></p>
<p>执行代码，输出结果为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">4 记录插入成功。</span><br><span class="line">`</span><br></pre></td></tr></table></figure></p>
<p>如果我们想在数据记录插入后，获取该记录的 ID ，可以使用以下代码：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"> </span><br><span class="line">sql = <span class="string">"INSERT INTO sites (name, url) VALUES (%s, %s)"</span></span><br><span class="line">val = (<span class="string">"Zhihu"</span>, <span class="string">"https://www.zhihu.com"</span>)</span><br><span class="line">mycursor.execute(sql, val)</span><br><span class="line"> </span><br><span class="line">mydb.commit()</span><br><span class="line"> </span><br><span class="line">print(<span class="string">"1 条记录已插入, ID:"</span>, mycursor.lastrowid)</span><br></pre></td></tr></table></figure></p>
<p>执行代码，输出结果为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">1 条记录已插入, ID: 6</span><br></pre></td></tr></table></figure></p>
<h6 id="查询数据"><a href="#查询数据" class="headerlink" title="查询数据"></a>查询数据</h6><ol>
<li>查询所有数据<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">mycursor.execute(<span class="string">"SELECT * FROM sites"</span>)</span><br><span class="line"> </span><br><span class="line">myresult = mycursor.fetchall()     <span class="comment"># fetchall() 获取所有记录</span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> myresult:</span><br><span class="line">  print(x)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>执行代码，输出结果为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">(1, &apos;RUNOOB&apos;, &apos;https://www.runoob.com&apos;)</span><br><span class="line">(2, &apos;Google&apos;, &apos;https://www.google.com&apos;)</span><br><span class="line">(3, &apos;Github&apos;, &apos;https://www.github.com&apos;)</span><br><span class="line">(4, &apos;Taobao&apos;, &apos;https://www.taobao.com&apos;)</span><br><span class="line">(5, &apos;stackoverflow&apos;, &apos;https://www.stackoverflow.com/&apos;)</span><br><span class="line">(6, &apos;Zhihu&apos;, &apos;https://www.zhihu.com&apos;)</span><br></pre></td></tr></table></figure></p>
<ol start="2">
<li>也可以读取指定的字段数据：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">mycursor.execute(<span class="string">"SELECT name, url FROM sites"</span>)</span><br><span class="line"> </span><br><span class="line">myresult = mycursor.fetchall()</span><br><span class="line"> </span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> myresult:</span><br><span class="line">  print(x)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>执行代码，输出结果为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">(&apos;RUNOOB&apos;, &apos;https://www.runoob.com&apos;)</span><br><span class="line">(&apos;Google&apos;, &apos;https://www.google.com&apos;)</span><br><span class="line">(&apos;Github&apos;, &apos;https://www.github.com&apos;)</span><br><span class="line">(&apos;Taobao&apos;, &apos;https://www.taobao.com&apos;)</span><br><span class="line">(&apos;stackoverflow&apos;, &apos;https://www.stackoverflow.com/&apos;)</span><br><span class="line">(&apos;Zhihu&apos;, &apos;https://www.zhihu.com&apos;)</span><br></pre></td></tr></table></figure></p>
<ol start="3">
<li>如果我们只想读取一条数据，可以使用 fetchone() 方法：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">mycursor.execute(<span class="string">"SELECT * FROM sites"</span>)</span><br><span class="line"> </span><br><span class="line">myresult = mycursor.fetchone()</span><br><span class="line"> </span><br><span class="line">print(myresult)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>执行代码，输出结果为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(1, &apos;RUNOOB&apos;, &apos;https://www.runoob.com&apos;)</span><br></pre></td></tr></table></figure></p>
<ol start="4">
<li>如果我们要读取指定条件的数据，可以使用 where 语句：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">sql = <span class="string">"SELECT * FROM sites WHERE name ='RUNOOB'"</span></span><br><span class="line"> </span><br><span class="line">mycursor.execute(sql)</span><br><span class="line"> </span><br><span class="line">myresult = mycursor.fetchall()</span><br><span class="line"> </span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> myresult:</span><br><span class="line">  print(x)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>执行代码，输出结果为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(1, &apos;RUNOOB&apos;, &apos;https://www.runoob.com&apos;)</span><br></pre></td></tr></table></figure></p>
<ol start="5">
<li>也可以使用通配符 %：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">sql = <span class="string">"SELECT * FROM sites WHERE url LIKE '%oo%'"</span></span><br><span class="line"> </span><br><span class="line">mycursor.execute(sql)</span><br><span class="line"> </span><br><span class="line">myresult = mycursor.fetchall()</span><br><span class="line"> </span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> myresult:</span><br><span class="line">  print(x)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>执行代码，输出结果为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">(1, &apos;RUNOOB&apos;, &apos;https://www.runoob.com&apos;)</span><br><span class="line">(2, &apos;Google&apos;, &apos;https://www.google.com&apos;)</span><br></pre></td></tr></table></figure></p>
<ol start="6">
<li>为了防止数据库查询发生 SQL 注入的攻击，我们可以使用 %s 占位符来转义查询的条件：</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">sql = <span class="string">"SELECT * FROM sites WHERE name = %s"</span></span><br><span class="line">na = (<span class="string">"RUNOOB"</span>, )</span><br><span class="line"> </span><br><span class="line">mycursor.execute(sql, na)</span><br><span class="line"> </span><br><span class="line">myresult = mycursor.fetchall()</span><br><span class="line"> </span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> myresult:</span><br><span class="line">  print(x)</span><br></pre></td></tr></table></figure>
<h6 id="排序"><a href="#排序" class="headerlink" title="排序"></a>排序</h6><p>查询结果排序可以使用 ORDER BY 语句，默认的排序方式为升序，关键字为 ASC，如果要设置降序排序，可以设置关键字 DESC。</p>
<ol>
<li>按 name 字段字母的升序排序：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">sql = <span class="string">"SELECT * FROM sites ORDER BY name"</span></span><br><span class="line"> </span><br><span class="line">mycursor.execute(sql)</span><br><span class="line"> </span><br><span class="line">myresult = mycursor.fetchall()</span><br><span class="line"> </span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> myresult:</span><br><span class="line">  print(x)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>执行代码，输出结果为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">(3, &apos;Github&apos;, &apos;https://www.github.com&apos;)</span><br><span class="line">(2, &apos;Google&apos;, &apos;https://www.google.com&apos;)</span><br><span class="line">(1, &apos;RUNOOB&apos;, &apos;https://www.runoob.com&apos;)</span><br><span class="line">(5, &apos;stackoverflow&apos;, &apos;https://www.stackoverflow.com/&apos;)</span><br><span class="line">(4, &apos;Taobao&apos;, &apos;https://www.taobao.com&apos;)</span><br><span class="line">(6, &apos;Zhihu&apos;, &apos;https://www.zhihu.com&apos;)</span><br></pre></td></tr></table></figure></p>
<ol start="2">
<li>降序排序实例：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">sql = <span class="string">"SELECT * FROM sites ORDER BY name DESC"</span></span><br><span class="line"> </span><br><span class="line">mycursor.execute(sql)</span><br><span class="line"> </span><br><span class="line">myresult = mycursor.fetchall()</span><br><span class="line"> </span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> myresult:</span><br><span class="line">  print(x)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>执行代码，输出结果为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">(6, &apos;Zhihu&apos;, &apos;https://www.zhihu.com&apos;)</span><br><span class="line">(4, &apos;Taobao&apos;, &apos;https://www.taobao.com&apos;)</span><br><span class="line">(5, &apos;stackoverflow&apos;, &apos;https://www.stackoverflow.com/&apos;)</span><br><span class="line">(1, &apos;RUNOOB&apos;, &apos;https://www.runoob.com&apos;)</span><br><span class="line">(2, &apos;Google&apos;, &apos;https://www.google.com&apos;)</span><br><span class="line">(3, &apos;Github&apos;, &apos;https://www.github.com&apos;)</span><br></pre></td></tr></table></figure>
<h6 id="限制查询的数据量"><a href="#限制查询的数据量" class="headerlink" title="限制查询的数据量"></a>限制查询的数据量</h6><p>指定起始位置，读取前 3 条记录.</p>
<p>例如，从第二条开始读取前 3 条记录：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">mycursor.execute(<span class="string">"SELECT * FROM sites LIMIT 3 OFFSET 1"</span>)  <span class="comment"># 0 为 第一条，1 为第二条，以此类推</span></span><br><span class="line"> </span><br><span class="line">myresult = mycursor.fetchall()</span><br><span class="line"> </span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> myresult:</span><br><span class="line">  print(x)</span><br></pre></td></tr></table></figure></p>
<p>执行代码，输出结果为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">(2, &apos;Google&apos;, &apos;https://www.google.com&apos;)</span><br><span class="line">(3, &apos;Github&apos;, &apos;https://www.github.com&apos;)</span><br><span class="line">(4, &apos;Taobao&apos;, &apos;https://www.taobao.com&apos;)</span><br></pre></td></tr></table></figure></p>
<h6 id="删除记录"><a href="#删除记录" class="headerlink" title="删除记录"></a>删除记录</h6><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">sql = <span class="string">"DELETE FROM sites WHERE name = 'stackoverflow'"</span></span><br><span class="line"> </span><br><span class="line">mycursor.execute(sql)</span><br><span class="line"> </span><br><span class="line">mydb.commit()</span><br><span class="line"> </span><br><span class="line">print(mycursor.rowcount, <span class="string">" 条记录删除"</span>)</span><br></pre></td></tr></table></figure>
<p>执行代码，输出结果为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">1  条记录删除</span><br></pre></td></tr></table></figure></p>
<p><strong>注意</strong>：要慎重使用删除语句，删除语句要确保指定了 WHERE 条件语句，否则会导致整表数据被删除。</p>
<p>为了防止数据库查询发生 SQL 注入的攻击，我们可以使用 %s 占位符来转义删除语句的条件：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sql = <span class="string">"DELETE FROM sites WHERE name = %s"</span></span><br><span class="line">na = (<span class="string">"stackoverflow"</span>, )</span><br></pre></td></tr></table></figure>
<h6 id="更新表数据"><a href="#更新表数据" class="headerlink" title="更新表数据"></a>更新表数据</h6><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">sql = <span class="string">"UPDATE sites SET name = 'ZH' WHERE name = 'Zhihu'"</span></span><br><span class="line"> </span><br><span class="line">mycursor.execute(sql)</span><br><span class="line"> </span><br><span class="line">mydb.commit()</span><br><span class="line"> </span><br><span class="line">print(mycursor.rowcount, <span class="string">" 条记录被修改"</span>)</span><br><span class="line">执行代码，输出结果为：</span><br></pre></td></tr></table></figure>
<p>使用 %s 占位符来转义更新语句的条件：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sql = <span class="string">"UPDATE sites SET name = %s WHERE name = %s"</span></span><br><span class="line">val = (<span class="string">"Zhihu"</span>, <span class="string">"ZH"</span>)</span><br></pre></td></tr></table></figure></p>
<h6 id="删除表"><a href="#删除表" class="headerlink" title="删除表"></a>删除表</h6><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">sql = <span class="string">"DROP TABLE IF EXISTS sites"</span>  <span class="comment"># 删除数据表 sites</span></span><br><span class="line"> </span><br><span class="line">mycursor.execute(sql)</span><br></pre></td></tr></table></figure>
<h4 id="PyMySQL-驱动"><a href="#PyMySQL-驱动" class="headerlink" title="PyMySQL 驱动"></a>PyMySQL 驱动</h4><p>PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库，Python2中则使用mysqldb。</p>
<p>PyMySQL 遵循 Python 数据库 API v2.0 规范，并包含了 pure-Python MySQL 客户端库。</p>
<h5 id="安装-2"><a href="#安装-2" class="headerlink" title="安装"></a>安装</h5><ol>
<li>命令：</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install PyMySQL</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>pycharm 的setting里面安装pymysql包</li>
</ol>
<h5 id="操作-1"><a href="#操作-1" class="headerlink" title="操作"></a>操作</h5><p>在操作之前确保：<br>1.您已经创建了数据库 TESTDB.<br>2.在TESTDB数据库中您已经创建了表 EMPLOYEE<br>3.EMPLOYEE表字段为 FIRST_NAME, LAST_NAME, AGE, SEX 和 INCOME。</p>
<h6 id="数据库连接"><a href="#数据库连接" class="headerlink" title="数据库连接"></a>数据库连接</h6><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pymysql</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 打开数据库连接</span></span><br><span class="line">db = pymysql.connect(<span class="string">"localhost"</span>,<span class="string">"testuser"</span>,<span class="string">"test123"</span>,<span class="string">"TESTDB"</span> )</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 使用 cursor() 方法创建一个游标对象 cursor</span></span><br><span class="line">cursor = db.cursor()</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 使用 execute()  方法执行 SQL 查询 </span></span><br><span class="line">cursor.execute(<span class="string">"SELECT VERSION()"</span>)</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 使用 fetchone() 方法获取单条数据.</span></span><br><span class="line">data = cursor.fetchone()</span><br><span class="line"> </span><br><span class="line"><span class="keyword">print</span> (<span class="string">"Database version : %s "</span> % data)</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 关闭数据库连接</span></span><br><span class="line">db.close()</span><br></pre></td></tr></table></figure>
<h6 id="创建数据库表"><a href="#创建数据库表" class="headerlink" title="创建数据库表"></a>创建数据库表</h6><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pymysql</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 打开数据库连接</span></span><br><span class="line">db = pymysql.connect(<span class="string">"localhost"</span>,<span class="string">"testuser"</span>,<span class="string">"test123"</span>,<span class="string">"TESTDB"</span> )</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 使用 cursor() 方法创建一个游标对象 cursor</span></span><br><span class="line">cursor = db.cursor()</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 使用 execute() 方法执行 SQL，如果表存在则删除</span></span><br><span class="line">cursor.execute(<span class="string">"DROP TABLE IF EXISTS EMPLOYEE"</span>)</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 使用预处理语句创建表</span></span><br><span class="line">sql = <span class="string">"""CREATE TABLE EMPLOYEE (</span></span><br><span class="line"><span class="string">         FIRST_NAME  CHAR(20) NOT NULL,</span></span><br><span class="line"><span class="string">         LAST_NAME  CHAR(20),</span></span><br><span class="line"><span class="string">         AGE INT,  </span></span><br><span class="line"><span class="string">         SEX CHAR(1),</span></span><br><span class="line"><span class="string">         INCOME FLOAT )"""</span></span><br><span class="line"> </span><br><span class="line">cursor.execute(sql)</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 关闭数据库连接</span></span><br><span class="line">db.close()</span><br></pre></td></tr></table></figure>
<h6 id="插入操作"><a href="#插入操作" class="headerlink" title="插入操作"></a>插入操作</h6><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 部分代码省略</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># SQL 插入语句</span></span><br><span class="line">sql = <span class="string">"""INSERT INTO EMPLOYEE(FIRST_NAME,</span></span><br><span class="line"><span class="string">         LAST_NAME, AGE, SEX, INCOME)</span></span><br><span class="line"><span class="string">         VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""</span></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">   <span class="comment"># 执行sql语句</span></span><br><span class="line">   cursor.execute(sql)</span><br><span class="line">   <span class="comment"># 提交到数据库执行</span></span><br><span class="line">   db.commit()</span><br><span class="line"><span class="keyword">except</span>:</span><br><span class="line">   <span class="comment"># 如果发生错误则回滚</span></span><br><span class="line">   db.rollback()</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 关闭数据库连接</span></span><br><span class="line">db.close()</span><br></pre></td></tr></table></figure>
<p>也可以写成如下形式：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># SQL 插入语句</span></span><br><span class="line">sql = <span class="string">"INSERT INTO EMPLOYEE(FIRST_NAME, \</span></span><br><span class="line"><span class="string">       LAST_NAME, AGE, SEX, INCOME) \</span></span><br><span class="line"><span class="string">       VALUES ('%s', '%s',  %s,  '%s',  %s)"</span> % \</span><br><span class="line">       (<span class="string">'Mac'</span>, <span class="string">'Mohan'</span>, <span class="number">20</span>, <span class="string">'M'</span>, <span class="number">2000</span>)</span><br></pre></td></tr></table></figure></p>
<h6 id="查询操作"><a href="#查询操作" class="headerlink" title="查询操作"></a>查询操作</h6><p>Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。</p>
<ul>
<li>fetchone(): 该方法获取下一个查询结果集。结果集是一个对象</li>
<li>fetchall(): 接收全部的返回结果行.</li>
<li>rowcount: 这是一个只读属性，并返回执行execute()方法后影响的行数。</li>
</ul>
<p>查询EMPLOYEE表中salary（工资）字段大于1000的所有数据：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># SQL 查询语句</span></span><br><span class="line">sql = <span class="string">"SELECT * FROM EMPLOYEE \</span></span><br><span class="line"><span class="string">       WHERE INCOME &gt; %s"</span> % (<span class="number">1000</span>)</span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">   <span class="comment"># 执行SQL语句</span></span><br><span class="line">   cursor.execute(sql)</span><br><span class="line">   <span class="comment"># 获取所有记录列表</span></span><br><span class="line">   results = cursor.fetchall()</span><br><span class="line">   <span class="keyword">for</span> row <span class="keyword">in</span> results:</span><br><span class="line">      fname = row[<span class="number">0</span>]</span><br><span class="line">      lname = row[<span class="number">1</span>]</span><br><span class="line">      age = row[<span class="number">2</span>]</span><br><span class="line">      sex = row[<span class="number">3</span>]</span><br><span class="line">      income = row[<span class="number">4</span>]</span><br><span class="line">       <span class="comment"># 打印结果</span></span><br><span class="line">      <span class="keyword">print</span> (<span class="string">"fname=%s,lname=%s,age=%s,sex=%s,income=%s"</span> % \</span><br><span class="line">             (fname, lname, age, sex, income ))</span><br><span class="line"><span class="keyword">except</span>:</span><br><span class="line">   <span class="keyword">print</span> (<span class="string">"Error: unable to fetch data"</span>)</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 关闭数据库连接</span></span><br><span class="line">db.close()</span><br></pre></td></tr></table></figure>
<h6 id="更新操作"><a href="#更新操作" class="headerlink" title="更新操作"></a>更新操作</h6><p>将 TESTDB 表中 SEX 为 ‘M’ 的 AGE 字段递增 1：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sql = <span class="string">"UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'"</span> % (<span class="string">'M'</span>)</span><br></pre></td></tr></table></figure>
<h6 id="删除操作"><a href="#删除操作" class="headerlink" title="删除操作"></a>删除操作</h6><p>删除数据表 EMPLOYEE 中 AGE 大于 20 的所有数据：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># SQL 删除语句</span></span><br><span class="line">sql = <span class="string">"DELETE FROM EMPLOYEE WHERE AGE &gt; %s"</span> % (<span class="number">20</span>)</span><br></pre></td></tr></table></figure></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>你可以对我进行打赏哦</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weichat.jpg" alt="ananzhusen 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="ananzhusen 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/MySQL/" rel="tag"># MySQL</a>
          
            <a href="/tags/python/" rel="tag"># python</a>
          
            <a href="/tags/PyMySQL/" rel="tag"># PyMySQL</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/04/11/学习Django框架/" rel="next" title="学习Django框架">
                <i class="fa fa-chevron-left"></i> 学习Django框架
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/28/QtCreator学习（1）/" rel="prev" title="QtCreator学习（1）">
                QtCreator学习（1） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/touxiang.JPG" alt="ananzhusen">
            
              <p class="site-author-name" itemprop="name">ananzhusen</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/ananzhusen" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5817162963" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gitee.com/anzhusen/" title="gitee" target="_blank">gitee</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#MySQL"><span class="nav-number">1.</span> <span class="nav-text">MySQL</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#安装"><span class="nav-number">1.1.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#MySQL常用命令"><span class="nav-number">1.2.</span> <span class="nav-text">MySQL常用命令</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#mysql-connector"><span class="nav-number">1.3.</span> <span class="nav-text">mysql-connector</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#安装-1"><span class="nav-number">1.3.1.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#操作"><span class="nav-number">1.3.2.</span> <span class="nav-text">操作</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#创建数据库连接"><span class="nav-number">1.3.2.1.</span> <span class="nav-text">创建数据库连接</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#创建数据库"><span class="nav-number">1.3.2.2.</span> <span class="nav-text">创建数据库</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#查看数据库"><span class="nav-number">1.3.2.3.</span> <span class="nav-text">查看数据库</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#创建数据表"><span class="nav-number">1.3.2.4.</span> <span class="nav-text">创建数据表</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#查看数据表是否已存在："><span class="nav-number">1.3.2.5.</span> <span class="nav-text">查看数据表是否已存在：</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#主键设置"><span class="nav-number">1.3.2.6.</span> <span class="nav-text">主键设置</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#插入数据"><span class="nav-number">1.3.2.7.</span> <span class="nav-text">插入数据</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#查询数据"><span class="nav-number">1.3.2.8.</span> <span class="nav-text">查询数据</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#排序"><span class="nav-number">1.3.2.9.</span> <span class="nav-text">排序</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#限制查询的数据量"><span class="nav-number">1.3.2.10.</span> <span class="nav-text">限制查询的数据量</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#删除记录"><span class="nav-number">1.3.2.11.</span> <span class="nav-text">删除记录</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#更新表数据"><span class="nav-number">1.3.2.12.</span> <span class="nav-text">更新表数据</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#删除表"><span class="nav-number">1.3.2.13.</span> <span class="nav-text">删除表</span></a></li></ol></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#PyMySQL-驱动"><span class="nav-number">1.4.</span> <span class="nav-text">PyMySQL 驱动</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#安装-2"><span class="nav-number">1.4.1.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#操作-1"><span class="nav-number">1.4.2.</span> <span class="nav-text">操作</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#数据库连接"><span class="nav-number">1.4.2.1.</span> <span class="nav-text">数据库连接</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#创建数据库表"><span class="nav-number">1.4.2.2.</span> <span class="nav-text">创建数据库表</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#插入操作"><span class="nav-number">1.4.2.3.</span> <span class="nav-text">插入操作</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#查询操作"><span class="nav-number">1.4.2.4.</span> <span class="nav-text">查询操作</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#更新操作"><span class="nav-number">1.4.2.5.</span> <span class="nav-text">更新操作</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#删除操作"><span class="nav-number">1.4.2.6.</span> <span class="nav-text">删除操作</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ananzhusen</span>

  
</div>

<!-- 
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>
 -->



        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数 <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站访问总量 <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'e69lyQSoCtoaLGljT3kXLBEQ-gzGzoHsz',
        appKey: 'pRDcFfyQnO4jQWxElUFupJ2D',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;"></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/src/fireworks.js"></script>
  

</body>
</html>
